#include "loginwidget.h"
#include "xmppmanager.h"
#include <QEvent>
#include <QLineEdit>
#include <QLayout>
#include <QSettings>
#include <QCheckBox>
#include <QPushButton>
#include <QKeyEvent>

#define SETTING_USERID  "userid"
#define SETTING_PASSWORD "passwprd"
#define SETTING_SAVE_PASSWORD "save_password"

LoginWidget::LoginWidget(QWidget *parent) :
    QWidget(parent),
    firstTime(true)
{
    XmppManager::instance().addLoginEventHandler(this);
}

LoginWidget::~LoginWidget()
{
    XmppManager::instance().removeLoginEventHandler(this);
}

CUSTOM_EVENT_MAP(LoginWidget) {
    CUSTOM_EVENT(EVENT_LOGIN, onLogin)
    CUSTOM_EVENT_WITH_PARAM(EVENT_LOGOFF, onLogoff, LogoffEvent, errorCode)
}

void LoginWidget::onLogin()
{
    setVisible(false);

}

void LoginWidget::onLogoff(int errorCode)
{
    Q_UNUSED(errorCode);
    setEnabled(true);
    setVisible(true);
    editLoginId->setEnabled(true);
    editPassword->setEnabled(true);
    checkSavePassword->setEnabled(true);
    buttonLogin->setEnabled(true);

}

void  LoginWidget::keyPressEvent(QKeyEvent *event)
{
    if (event->key() == Qt::Key_Return)
    {
        if (isEnabled())
            loginButtonClicked();
    }

}

bool LoginWidget::event(QEvent *myEvent)
{
//    std::clog << "EVENT:" << myEvent->type() << std::endl;

    if (myEvent->type() == QEvent::Show)
    {
        if (isVisible() && firstTime) {
            firstTime = false;
            QSettings setting;
            editLoginId = qFindChild<QLineEdit*>(this, "EditLoginId");
            editPassword = qFindChild<QLineEdit*>(this, "EditPassword");
            checkSavePassword = qFindChild<QCheckBox*>(this, "SavePassword");
            buttonLogin = qFindChild<QPushButton*>(this, "ButtonLogin");

            QString strLoginId = setting.value(SETTING_USERID).value<QString>();
            QString strPassword = setting.value(SETTING_PASSWORD).value<QString>();
            bool bcheckSavePassword = setting.value(SETTING_SAVE_PASSWORD).value<bool>();
            editLoginId->setText(strLoginId);
            if (bcheckSavePassword)
            {
                editPassword->setText(strPassword);
            }
            checkSavePassword->setChecked(bcheckSavePassword);

        }
    }
    return QWidget::event(myEvent);
}

void LoginWidget::loginButtonClicked()
{
    QString strLoginId = editLoginId->text();
    QString strPassword = editPassword->text();
    bool bcheckSavePassword = checkSavePassword->checkState();

    setEnabled(false);
    editLoginId->setEnabled(false);
    editPassword->setEnabled(false);
    checkSavePassword->setEnabled(false);
    buttonLogin->setEnabled(false);


    QSettings setting;
    setting.setValue(SETTING_USERID, strLoginId);
    setting.setValue(SETTING_PASSWORD, strPassword);
    setting.setValue(SETTING_SAVE_PASSWORD, bcheckSavePassword);
    XmppManager::instance().login(strLoginId, strPassword);


}
